package school.xauat.现代密码学.消息摘要;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author ：zsy
 * @date ：Created 2021/6/17 15:59
 * @description：消息摘要
 */
public class DigestDemo1 {

    public static void main(String[] args) throws Exception {
        String input = "aa";
        //算法
        String algorithm = "MD5";
        String encryptMD5 = getDigest(input, algorithm);
        System.out.println(encryptMD5);

        String encryptSHA1 = getDigest(input, "SHA-1");
        System.out.println(encryptSHA1);
        String encryptSHA256 = getDigest(input, "SHA-256");
        System.out.println(encryptSHA256);
        String encryptSHA512 = getDigest(input, "SHA-512");
        System.out.println(encryptSHA512);

        String digestFile = getDigestFile("article.txt", "SHA-1");
        System.out.println(digestFile);
    }

    public static String getDigest(String input, String algorithm) throws NoSuchAlgorithmException {
        //创建消息摘要对象
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        //执行消息摘要算法
        byte[] digest = messageDigest.digest(input.getBytes());
        System.out.println(algorithm + "加密密文长度：" +  digest.length);
        return toHex(digest);
    }

    private static String toHex(byte[] digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest) {
            String string = Integer.toHexString(b & 0xff);
            string = string.length() > 1 ? string : "0" + string;
            builder.append(string);
        }
        return builder.toString();
    }

    public static String getDigestFile(String filePath, String algorithm) throws Exception {
        FileInputStream fis = new FileInputStream(filePath);
        int len;
        byte[] buffer = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while((len = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        byte[] digest = messageDigest.digest(baos.toByteArray());
        System.out.println(algorithm + "加密密文长度：" + digest.length);
        return toHex(digest);
    }
}
